package com.zhudi.develop_demo_as.ui.fragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.AlertDialogWrapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zhudi.develop.util.ZhudiDebugLog;
import com.zhudi.develop.util.ZhudiImageUtil;
import com.zhudi.develop.util.ZhudiToastSingle;
import com.zhudi.develop.view.ZhudiCircularImage;
import com.zhudi.develop_demo_as.BaseFragment;
import com.zhudi.develop_demo_as.MainApplication;
import com.zhudi.develop_demo_as.R;
import com.zhudi.develop_demo_as.ui.activity.BookActivity;
import com.zhudi.develop_demo_as.ui.activity.OrderListActivity;
import com.zhudi.develop_demo_as.ui.activity.pic.PhotoPickerActivity;
import com.zhudi.develop_demo_as.utils.ImageCaptureManager;
import com.zhudi.develop_demo_as.utils.Variables;

import org.apache.http.Header;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class MineFragment extends BaseFragment{
	/**选择图片 */
	public final static int REQUEST_CODE = 1;
	/**相机 */
	public final static int CAMERA_CODE = 2;
	/**裁切图片 */
	public final static int CUT_CODE = 3;
	@Bind(R.id.tvTitle)
	TextView tvTitle;
	@Bind(R.id.sv)
	View sv;
	@Bind(R.id.user_icon)
	ZhudiCircularImage ivUsercon;

	private ImageCaptureManager captureManager;
	@Override
	protected int getLayoutView() {
		return R.layout.fragment_mine;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		captureManager = new ImageCaptureManager(getActivity());
		initView();
	}

	private void initView() {
		tvTitle.setText("我的");
		sv.setOverScrollMode(View.OVER_SCROLL_NEVER);
	}

	//选择图片或拍照
	@OnClick(R.id.user_icon)
	public void onClickUserPic(){
		showGetPictureDialog();
	}

	//团购订单
	@OnClick(R.id.group_order_container)
	public void onClickOrder(){
		startActivity(new Intent(getActivity(), OrderListActivity.class));
	}

	//预定订单
	@OnClick(R.id.reserve_order_container)
	public void onClickBook(){
		startActivity(new Intent(getActivity(), OrderListActivity.class));
	}

	//外卖单
	@OnClick(R.id.take_out_container)
	public void onClickTakeOut(){
		startActivity(new Intent(getActivity(), BookActivity.class));
	}

	private void showGetPictureDialog() {
		new AlertDialogWrapper.Builder(getActivity())
				.setItems(R.array.head_pic, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
							case 0: // 相册
								Intent intentThree = new Intent();
								intentThree.setClass(getActivity(), PhotoPickerActivity.class);
								intentThree.putExtra(PhotoPickerActivity.EXTRA_MAX_COUNT, 1);
								intentThree.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, false);
								startActivityForResult(intentThree, REQUEST_CODE);
								break;
							case 1:  // 拍照
								try {
									Intent intent = captureManager.dispatchTakePictureIntent();
									startActivityForResult(intent, CAMERA_CODE);
								} catch (IOException e) {
									e.printStackTrace();
								}
								break;
						}
					}
				})
				.show();
	}
//
//	private void getLastPhoto() {
//		new AsyncTask<Void, Void, String>() {
//			@Override
//			public String doInBackground(Void... params){
//				String path = "";
//				if (getActivity() != null)
//					path = "";
//					//path = Utils.getLatestCameraPicture(getActivity());
//				return path;
//			}
//
//			@Override
//			protected void onPostExecute(String result) {
//				super.onPostExecute(result);
//				if (!ZhudiStrUtil.isEmpty(result)) {
//					ZhudiDebugLog.d("最近拍摄照片, path = " + result);
//					File file = new File(result);
//					if (file.exists() && file.length() == 0) {
//						ZhudiToastSingle.showToast(MainApplication.getInstance(), getActivity().getString(R.string.publish_get_recent_pic_faild), Toast.LENGTH_SHORT, -1);
//					} else {
//
//					}
//				}
//				else {
//					ZhudiToastSingle.showToast(MainApplication.getInstance(), getActivity().getString(R.string.publish_recent_pic_none), Toast.LENGTH_SHORT, -1);
//				}
//			}
//		}.execute();
//	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		List<String> photos = null;
		if (resultCode == Activity.RESULT_OK ) {
			if (requestCode == REQUEST_CODE)  {//相册图片选择返回
				if (data != null) {
					photos = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
				}
				if (photos != null){
					goCutPic(photos.get(0));
				}
			} else if(requestCode == CAMERA_CODE){ //相机拍照图片返回
				captureManager.galleryAddPic();
				if (captureManager != null) {
					String path = captureManager.getCurrentPhotoPath();
					goCutPic(path);
				}
			} else if (requestCode == CUT_CODE) { //拿到剪切数据
				Bitmap bmap = data.getParcelableExtra("data");
				if (bmap != null) {
					ivUsercon.setImageBitmap(bmap);
					String filePath = Variables.APP_PIC_SDPATH + File.separator + ZhudiImageUtil.getTempFileName() + ".png";
					try {
						ZhudiImageUtil.saveImageToSD(getActivity(), filePath, bmap, 100);
					}  catch (IOException e) {
						e.printStackTrace();
					}
					File file = new File(filePath);
					if (!file.exists()) {
						ZhudiToastSingle.showToast(MainApplication.getInstance(), getActivity().getString(R.string.no_img), Toast.LENGTH_SHORT, -1);
					}
					RequestParams params = new RequestParams();
					try {
						params.put("file",new File[]{file});
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					new AsyncHttpClient().post(MainApplication.getInstance(), "http://10.21.107.115:8080/javaecshop/data/data!uploadFile", params, new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
							ZhudiDebugLog.d(new String(responseBody));
						}

						@Override
						public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
							ZhudiDebugLog.d(String.valueOf(statusCode));
						}
					});
				}
			}
		}
	}

	/**去裁切图片 */
	private void goCutPic(String picPath) {
		Intent intent = new Intent();
		intent.setAction("com.android.camera.action.CROP");
		intent.setDataAndType(Uri.fromFile(new File(picPath)), "image/*");// mUri是已经选择的图片Uri
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);// 裁剪框比例
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 120);// 输出图片大小
		intent.putExtra("outputY", 120);
		intent.putExtra("return-data", true);
		intent.putExtra("scale", true);// 去黑边
		intent.putExtra("scaleUpIfNeeded", true);// 去黑边
		startActivityForResult(intent, MineFragment.CUT_CODE);
	}
}
